#include "../../Header/AppCore/ObjectMesh.h"

ObjectMesh::ObjectMesh()
	:m_VBO(-1), m_IBO(-1), m_strSRC(NULL),
	m_VBO_Size(0), m_IBO_Size(0),
	m_IsGrayScale(false)
{

}

ObjectMesh::ObjectMesh(ObjectMesh* objm)
{
	m_VBO = objm->GetVBO();
	m_IBO = objm->GetIBO();
	_utInt16 size = strlen(objm->GetSRC()) + 1;
	m_strSRC = new char[size];
	strcpy(m_strSRC, objm->GetSRC());
	m_VBO_Size = objm->GetVBOSize();
	m_IBO_Size = objm->GetIBOSize();
}

ObjectMesh::ObjectMesh(GLuint vbo, GLuint vbo_size, GLuint ibo, GLuint ibo_size)
{
	m_VBO = vbo;
	m_IBO = ibo;
	m_VBO_Size = vbo_size;
	m_IBO_Size = ibo_size;
}

GLuint ObjectMesh::BindData(Vertex* vertices,GLuint numVertices, GLushort* indices, GLuint numIndices)
{
	LOGI("GrayScale = %d\n", m_IsGrayScale);
	if (!vertices || numVertices <= 0)
		return -1;

	m_VBO_Size = numVertices;
	glGenBuffers(1, &m_VBO);
	glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
	glBufferData(GL_ARRAY_BUFFER, m_VBO_Size*sizeof(Vertex), vertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	if (indices)
	{
		if (numIndices <= 0)
			return -1;

		m_IBO_Size = numIndices;
		glGenBuffers(1, &m_IBO);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_IBO_Size*sizeof(GLushort), indices, GL_STATIC_DRAW);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	}

	return 0;
}

GLuint ObjectMesh::BindLocation(ObjectShader* sha, Matrix)
{
	glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
	if (sha->m_Position != -1)
	{
		glEnableVertexAttribArray(sha->m_Position);
		glVertexAttribPointer(sha->m_Position, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if (sha->m_Color != -1)
	{
		glEnableVertexAttribArray(sha->m_Color);
		glVertexAttribPointer(sha->m_Color, 4, GL_UNSIGNED_SHORT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3));
	}
	if (sha->m_UV != -1)
	{
		glEnableVertexAttribArray(sha->m_UV);
		glVertexAttribPointer(sha->m_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3) + sizeof(Vector4));
	}
	if (sha->m_GrayScaleOption != -1)
	{
		glUniform1i(sha->m_GrayScaleOption, m_IsGrayScale);
	}

	if (m_IBO_Size > 0)
	{
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
	}

	return 0;
}

GLuint ObjectMesh::UnBindLocaction()
{
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	return 0;
}


GLuint ObjectMesh::Destroy()
{
	SAFE_DEL_ARRAY(m_strSRC);
	glDeleteBuffers(1, &m_VBO);
	glDeleteBuffers(1, &m_IBO);
	return 0;
}